import { makeAutoObservable, } from "mobx";
import { showError } from "../components/Message";
import { NewsData, NewsItem, NewsService } from "../services/NewsService";

class NewsStore {
  public loading: boolean = false;
  public loadingMore: boolean = false;
  public newsList: NewsItem[] = [];
  private _page: number = 1;
  private noMore: boolean = false;

  constructor() {
    makeAutoObservable(this);
  }

  public async getData(loadmore?: boolean) {

    if (this.loading || this.loadingMore) {
      return;
    }
    let response: NewsData;

    if (loadmore) {
      if (this.noMore) {
        return;
      }
      this.loadingMore = true;
      this._page += 1;
    } else {
      this.loading = true;
      this._page = 1;
    }

    try {
      response = await new NewsService('', '', this._page).send();
    } catch (e: any) {
      this.loading = false;
      showError(e);
      return;
    }
    this.loading = false;
    this.loading = false;
    this.loadingMore = false;
    if (loadmore) {
      this.noMore = response.list.length === 0;
      this.newsList.push(...response.list);
    } else {
      this.newsList = response.list;
    }
  }

}

const newsStore = new NewsStore();

export { newsStore };